/*
Copyright (c)2009 Seesmic, Inc

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package com.seesmic.twhix
{

	
	public class MaskHandler extends XMLHandler {
		public var searchXML:XML;

		
		public function MaskHandler(search:String, pointer:Function=null, use_once:Boolean=false) {
			searchXML = XML(search);
			super(search, pointer, use_once);
		}
		
		override public function match(xdoc:XML):Boolean {
			return nodeCompare(searchXML, xdoc)
			//for each(var element:XMLNode in searchXML.childNodes) {
		}
		
		private function nodeCompare(searchNode:XML, findNode:XML):Boolean {
			//trace(findNode.nodeName);
			if(searchNode.localName() != findNode.localName()) {
				//trace(searchNode.nodeName + "!=" + curnode);
				return false;
			}
			if(findNode.namespace() != searchNode.namespace()) {
				return false;
			}
			if(searchNode.text() && findNode.text() != searchNode.text()) {
				return false;
			}
			for each(var attr:Object in searchNode.attributes) {
				//trace ("**" + attr); // um, that's not helpful
			}
			var found:Boolean = false;
			for each(var searchSub:XML in searchNode.children()) {
				for each(var findSub:XML in findNode.children()) {
					if(nodeCompare(searchSub, findSub)) {
						found = true;
						break;
					}
				}
				if(!found) return false;
				found = false;
			}
			//trace("match!");
			return true;
		}
	}
}
